package com.lzxuni.modules.organization.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzxuni.common.annotation.SysLog;
import com.lzxuni.common.constant.LogConstant;
import com.lzxuni.common.utils.FileUtil;
import com.lzxuni.common.utils.R;
import com.lzxuni.common.utils.StringUtils;
import com.lzxuni.common.utils.date.DateUtil;
import com.lzxuni.common.utils.poi.ExcelUtil;
import com.lzxuni.modules.common.controller.BaseController;
import com.lzxuni.modules.common.entity.Tree;
import com.lzxuni.modules.organization.entity.Company;
import com.lzxuni.modules.organization.service.CooperativeService;
import com.lzxuni.modules.system.entity.BaseArea;
import com.lzxuni.modules.system.service.BaseAreaService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("/LR_OrganizationModule/Cooperative")
public class CooperativeController extends BaseController {
	@Autowired
	private CooperativeService cooperativeService;
	@Autowired
	private BaseAreaService baseAreaService;
	// 列表
	@SysLog(categoryId = LogConstant.VIEWID,module = "合作社管理",operateType = LogConstant.VIEW)
	@RequestMapping("/index")
	public ModelAndView index() {
		ModelAndView mv = new ModelAndView("/LR_OrganizationModule/Cooperative/index");
		return mv;
	}
	// 部门列表
	@RequestMapping("/GetList")
	public Object GetList(String areaId) {
		return R.ok().put("data", cooperativeService.list(new QueryWrapper<Company>()
				.eq("nature", "cooperative")
				.eq("county_id", areaId)));
	}
	// 根据parentId查找
	@RequestMapping("/GetTree")
	public Object GetTree(String parentId)  {
		List<Tree> companyList = cooperativeService.getTree(parentId);
		return R.ok().put("data",companyList);
	}

	// 添加展示页面
	@RequestMapping("/Form")
	public ModelAndView insert(String parentId){
		ModelAndView mv = new ModelAndView("/LR_OrganizationModule/Cooperative/form");
		return mv;
	}
	@SysLog(categoryId = LogConstant.OPERATEID,module = "合作社管理",operateType = LogConstant.INSERT)
	@RequestMapping("/SaveForm")
	public Object insertDo(String keyValue, Company company) {
		company.setCompanyId(keyValue);
		if(StringUtils.isEmpty(company.getCompanyId())){
			cooperativeService.insert(getUser(), company);
			return R.ok("保存成功");
		}else{
			cooperativeService.update(getUser(), company);
			return R.ok("修改成功");
		}
	}

	//公司管理删除
	@SysLog(categoryId = LogConstant.OPERATEID,module = "合作社管理",operateType = LogConstant.DELETE)
	@RequestMapping("/DeleteForm")
	public Object delete(String keyValue) {
		cooperativeService.removeById(keyValue);
		return R.ok("删除成功");
	}

	@RequestMapping("/GetMap")
	public Object getMap(String ver){

//		return R.ok("no update");
		return R.ok("响应成功").put("data",cooperativeService.getMap(ver));
	}

	//根据类型nature 查询base_company
	@RequestMapping("/GetSelectTree")
	public Object GetSelectTree(String nature)  {
		List<Tree> companyList = cooperativeService.getTreeSelectTree(nature, getUser());
		return R.ok().put("data",companyList);
	}
	//初始化合作联社
	@RequestMapping("/cooperativeAssociationTree")
	public Object cooperativeAssociationTree(String nature,String parentId)  {
		Map map = new HashMap();
		if("".equals(parentId) || parentId == null){
			map.put("nature", nature);
			map.put("parentId", parentId);
			/*这个位置写死了不行,正常是根据parentId 查询为了应付检查第一层固定的下拉选*/
			map.put("Id1", "6e3f12783e386a45900529019e3ef009");
			map.put("Id2", "57546d7f981a11c0ef562d8541727c3a");
			map.put("Id3", "25be0eb3926f4b0cb0cbbebee1d577dd");
		}else{
			map.put("nature", nature);
			map.put("parentId", parentId);
		}
		List<Tree> companyList = cooperativeService.cooperativeAssociationTree(map);
		return R.ok().put("data",companyList);
	}

	//导入合作社，页面
	@RequestMapping("/ImportForm")
	public ModelAndView ImportForm(String keyValue, Company company) {
		ModelAndView mv = new ModelAndView("/LR_OrganizationModule/Cooperative/ImportForm");
		return mv;
	}
	//进行导入的操作,由于导出和导入的表时一样的所以我们直接可以用导出的表作为模板，进行导入的操作
	@RequestMapping("/ImportFormDo")
	public Object ImportFormDo(MultipartFile inputFile, HttpServletRequest request, String keyValue){
		Map<String, String> map =null;
		// 判断文件是否为空
		if (!inputFile.isEmpty()) {
			try {
				String originalFilename = inputFile.getOriginalFilename();//原文件名字
				InputStream is = inputFile.getInputStream();//获取输入流
				map = cooperativeService.readExcelData(is,originalFilename,keyValue,getUser());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return R.ok().put("data",map);
	}

	/**
	 * 利用工具类导出
	 * @param response
	 * @param keyValue
	 * @return
	 */
	@RequestMapping("/exportForm")
	public void exportForm(HttpServletResponse response, String keyValue, HttpServletRequest request)  {
		BufferedOutputStream fos = null;
		try {
			//一个sheet
			LinkedHashMap<String, List<List<String>>> dataMap = new LinkedHashMap<>();
			List<Company> listCompany = cooperativeService.list(new QueryWrapper<Company>()
															.eq("nature", "cooperative")
															.eq("county_id", keyValue));
			//我们要将上面的对象转换成一个list数组
			List<List<String>> listData = new ArrayList<>();
			List<String> list0 = new ArrayList<>();
			list0.add("名称*");
			list0.add("编码*");
			list0.add("简称*");
			list0.add("负责人");
			list0.add("负责人电话");
			list0.add("业务联系人");
			list0.add("联系人电话");
			list0.add("省*");
			list0.add("市*");
			list0.add("县*");
			list0.add("镇");
			list0.add("村");
			list0.add("详细地址");
			list0.add("备注");
			listData.add(list0);
			for (Company company : listCompany) {
				//每次遍历一个对象就要将对象转换成list 然后装进listData中
				List<String> list = new ArrayList<>();
				list.add(company.getFullName());
				list.add(company.getEnCode());
				list.add(company.getShortName());
				list.add(company.getManager());
				list.add(company.getOuterPhone());
				list.add(company.getLxr());
				list.add(company.getLxrPhone());
				/**
				 * 先根据id查询出区域的名字再放进list中
				 */
				BaseArea proArea = baseAreaService.getOne(new QueryWrapper<BaseArea>().eq("area_id",company.getProvinceId()));
				if(proArea !=null){
					list.add(proArea.getAreaName());
				}
				BaseArea cityArea = baseAreaService.getOne(new QueryWrapper<BaseArea>().eq("area_id",company.getCityId()));
				if(cityArea !=null){
					list.add(cityArea.getAreaName());
				}
				BaseArea countyArea = baseAreaService.getOne(new QueryWrapper<BaseArea>().eq("area_id",company.getCountyId()));
				if(countyArea !=null){
					list.add(countyArea.getAreaName());
				}
				BaseArea townArea = baseAreaService.getOne(new QueryWrapper<BaseArea>().eq("area_id",company.getTownId()));
				if(townArea !=null){
					list.add(townArea.getAreaName());
				}
				BaseArea villageArea = baseAreaService.getOne(new QueryWrapper<BaseArea>().eq("area_id",company.getVillageId()));
				if(villageArea !=null){
					list.add(villageArea.getAreaName());
				}
				list.add(company.getAddress());
				list.add(company.getDescription());
				//每遍历一个就放进listData中
				listData.add(list);
			}
			//sheet的标题和里面的数据
			if("downloadModel".equals(keyValue)){
				dataMap.put("合作社", listData);
				ExcelUtil excelUtil = new ExcelUtil();
				Workbook wb = excelUtil.writeExcel(dataMap, "合作社数据");
				String filename = "合作社模板"+".xls";
				String agent = request.getHeader("User-Agent");
				filename = FileUtil.encodeDownloadFilename(filename, agent);
				String contentType = request.getSession().getServletContext().getMimeType(filename);
				response.setContentType(contentType);
				response.setHeader("content-disposition", "attchment;filename=" + filename);
				fos = new BufferedOutputStream(response.getOutputStream());
				wb.write(fos);
			}else{
				dataMap.put("合作社", listData);
				ExcelUtil excelUtil = new ExcelUtil();
				Workbook wb = excelUtil.writeExcel(dataMap, "合作社导出数据");
				String filename = "合作社数据"+ DateUtil.DateToString(new Date(),"yyyyMMddHHmmss")+".xls";
				String agent = request.getHeader("User-Agent");
				filename = FileUtil.encodeDownloadFilename(filename, agent);
				String contentType = request.getSession().getServletContext().getMimeType(filename);
				response.setContentType(contentType);
				response.setHeader("content-disposition", "attchment;filename=" + filename);
				fos = new BufferedOutputStream(response.getOutputStream());
				wb.write(fos);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
